package radiostation.common;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;

public class AbstractRepository<T> {

    EntityManager entityManager;
    Class<T> type;

    public AbstractRepository(EntityManager em, Class<T> type) {
        entityManager = em;
        this.type = type;
    }

    public List<T> findAll() {
        Query q = entityManager.createNamedQuery(getModelName() + ".findAll", type);
        ArrayList<T> eList = new ArrayList<>(q.getResultList());
        return eList;
    }

    public T findById(Integer id) {
        Query q = entityManager.createNamedQuery(getModelName() + ".findBy" + getModelName() + "Id", type);
        q.setParameter(Utilities.firstLetterLower(getModelName()) + "Id", id);
        return (T) q.getSingleResult();
    }

    public T findByPropertyName(String propertyName, Object value) {
        try {
            Query q = entityManager.createNamedQuery(getModelName() + ".findBy" + propertyName, type);
            q.setParameter(Utilities.firstLetterLower(propertyName), value);
            return (T) q.getSingleResult();
        } catch (Exception e) {
            return null;
        }

    }

    private String getModelName() {
        String typeName = this.type.getName();
        String replace = typeName.replace("model.", "");
        return replace;
    }

}
